package org.example.managere.service.feibiao.impl;

import lombok.RequiredArgsConstructor;
import org.example.managere.dto.feibiao.AmAapInputDto;
import org.example.managere.entity.feibiao.AmAapInput;
import org.example.managere.repository.feibiao.AmAapInputRepository;
import org.example.managere.service.feibiao.AmAapInputService;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class AmAapInputServiceImpl implements AmAapInputService {
    private final AmAapInputRepository repository;
    private final ModelMapper modelMapper;

    private AmAapInputDto convertToDto(AmAapInput entity) {
        return modelMapper.map(entity, AmAapInputDto.class);
    }

    private AmAapInput convertToEntity(AmAapInputDto dto) {
        return modelMapper.map(dto, AmAapInput.class);
    }

    @Override
    @Transactional
    public AmAapInputDto save(AmAapInputDto dto) {
        AmAapInput entity = convertToEntity(dto);
        AmAapInput saved = repository.save(entity);
        return convertToDto(saved);
    }

    @Override
    @Transactional
    public AmAapInputDto update(Integer id, AmAapInputDto dto) {
        Optional<AmAapInput> optional = repository.findById(id);
        if (!optional.isPresent()) throw new RuntimeException("记录不存在");
        AmAapInput entity = convertToEntity(dto);
        entity.setId(id);
        AmAapInput saved = repository.save(entity);
        return convertToDto(saved);
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        repository.deleteById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<AmAapInputDto> findById(Integer id) {
        return repository.findById(id).map(this::convertToDto);
    }

    @Override
    @Transactional(readOnly = true)
    public Page<AmAapInputDto> findAll(Pageable pageable) {
        return repository.findAll(pageable).map(this::convertToDto);
    }

    @Override
    @Transactional(readOnly = true)
    public Page<AmAapInputDto> search(String keyword, Pageable pageable) {
        Specification<AmAapInput> spec = (root, query, cb) -> {
            if (keyword == null || keyword.isEmpty()) return null;
            return cb.or(
                cb.like(root.get("operatingMode"), "%" + keyword + "%"),
                cb.like(root.get("freqVibration"), "%" + keyword + "%")
            );
        };
        return repository.findAll(spec, pageable).map(this::convertToDto);
    }
} 